<template>
  <form id="grayPublish" ref="grayPublish">
    <h1 class="title">工作区灰度设置</h1>
    <div class="container-box">
    <div class="toolbar">
      <el-button @click="addGruop" type="primary" size="mini">增加</el-button>
      <!-- <el-button @click="modifyGruop" type="primary" size="mini">编辑</el-button>
      <el-button @click="deleteGruop" type="primary" size="mini">删除</el-button> -->
      <!-- <el-button @click="bindUser" type="primary" size="mini">绑定用户</el-button>
      <el-button @click="unBind" type="primary" size="mini">解除绑定</el-button> -->
    </div>
    <div class="main-cont">
      <el-table v-loading="loading" :data="tableData" :height="height" highlight-current-row @current-change="handleCurrentChange">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="workspaceId" label="工作区Id"></el-table-column>
        <el-table-column prop="groupName" label="组名" min-width="120"></el-table-column>
        <el-table-column label="状态" min-width="120">
          <template slot-scope="props">
            {{props.row.effected === true ? '已生效' : '未生效'}}
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="props">
            {{props.row.createTime | capitalize }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="100">
          <template slot-scope="scope">
            <el-button @click="handlePublishClick(scope.row)" type="text" size="mini" :disabled="scope.row.effected">
              <span v-if="scope.row.effected">已发布</span>
              <span v-else>发布</span>
            </el-button>
            <el-button @click="handleRepealClick(scope.row)" type="text" size="mini" :disabled="!scope.row.effected">置为失效</el-button>
            <!-- <el-button type="text" size="mini">绑定</el-button>
            <el-button type="text" size="mini">清空</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="currentChange"
        :current-page="currentPage"
        :page-size="pagesize"
        layout="total, prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
     </div>
    <!--下面放弹框 增删改-->
    <el-dialog title="新增" :visible.sync="dialogFlag" width="900px" top="200px">
      <el-form :model="groupData" ref="groupForm" :rules="workSPAddRules">
        <el-row>
          <el-col :span="12">
            <!-- <el-form-item label="用户分群名" prop="groupName">
              <el-input v-model="groupData.groupName"></el-input>
            </el-form-item> -->
            <el-form-item label="工作区选择" prop="workspaceId">
              <el-select v-model="groupData.workspaceId" placeholder="请选择" popper-class="zIndex-popper">
                <el-option
                  v-for="item in workSpList"
                  :key="item.Id"
                  :label="item.Name"
                  :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="用户分群ID" prop="groupId">
              <el-input v-model="groupData.groupId" :disabled="title !== 'ADD'"></el-input>
            </el-form-item> -->
            <el-form-item label="灰度用户组选择" prop="groupId">
              <el-select v-model="groupData.groupId" placeholder="请选择" popper-class="zIndex-popper">
                <el-option
                  v-for="item in whiteList"
                  :key="item.id"
                  :label="item.groupName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row class="f-rt">
        <!-- <el-button size="mini" @click="rest">重置</el-button> -->
        <el-button size="mini" @click="close">关闭</el-button>
        <el-button type="primary" size="mini" @click="submit">确定</el-button>
      </el-row>
    </el-dialog>
    <!-- 绑定用户与解绑的弹框 -->
    <el-dialog :title="dialogTitle === 'bind' ? '绑定用户' : '解除绑定'" :visible.sync="bindDialogFlag" width="900px" top="200px">
        <!-- kkopko -->
      <!-- <el-select v-model="selectCity" @change="uFilterCities" clearable placeholder="选择地区进行筛选" popper-class="zIndex-popper" size="mini" style="float: right; margin-bottom: 20px;">
        <el-option
          v-for="city in cities"
          :key="city.id"
          :label="city.userArea"
          :value="city.userArea">
        </el-option>
      </el-select> -->
      <el-row :gutter="20">
        <el-col :span="5">
          <!-- 开始时间选择框 -->
          <el-date-picker v-model="searchDataGroup.startTime" value-format="yyyyMMdd" align="right" type="date" placeholder="选择开始日期" size="mini" :picker-options="pickerOptions1" popper-class="zIndex-popper"></el-date-picker>
        </el-col>
        <el-col :span="5">
          <!-- 结束时间选择框 -->
          <el-date-picker v-model="searchDataGroup.endTime" value-format="yyyyMMdd" align="right" type="date" placeholder="选择结束日期" size="mini" :picker-options="pickerOptions1" popper-class="zIndex-popper"></el-date-picker>
        </el-col>
        <el-col :span="5">
          <!-- 机型 -->
          <el-input type="text" placeholder="输入机型" v-model="searchDataGroup.deviceType" size="mini">
            <!-- <el-button slot="append" icon="el-icon-search"></el-button> -->
          </el-input>
        </el-col>
        <el-col :span="5">
          <!-- 系统 -->
          <el-input type="text" placeholder="输入系统" v-model="searchDataGroup.systemType" size="mini">
            <!-- <el-button slot="append" icon="el-icon-search"></el-button> -->
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button icon="el-icon-search" size="mini" type="primary" @click="searchUser"></el-button>
        </el-col>
      </el-row>
      <el-table :data="dialogTitle === 'bind' ? unBindGroupData : bindGroupData" @select-all="selectAll" @select="select">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="用户ID" min-width="120"></el-table-column>
        <el-table-column prop="deviceType" label="设备型号" min-width="120"></el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登入时间" min-width="120"></el-table-column>
        <el-table-column prop="systemType" label="系统类型" min-width="120"></el-table-column>
        <!-- <el-table-column prop='userArea' label="地区" min-width="120"></el-table-column> -->
      </el-table>
      <el-row class="f-rt">
        <!-- <el-button size="mini" @click="bindRest">重置</el-button> -->
        <el-button size="mini" @click="bindClose">关闭</el-button>
        <!-- 绑定用户的确定 -->
        <el-button v-if="dialogTitle === 'bind'" type="primary" size="mini" @click="bindSubmit">确定</el-button>
        <!-- 解除绑定用户的确定 -->
        <el-button v-else type="primary" size="mini" @click="unBindSubmit">确定</el-button>
      </el-row>
    </el-dialog>
    <!-- 解除绑定的弹框 -->
  </form>
</template>
<script>
  import { VHeader } from '../../../../components'
  import '../../../../assets/css/mixinParameterManager.styl'
  import api from '../../../../api/url'
  import rules from '../../js/formRules'
  import ajax from '../../../../api/ajax/ajax'
  import { mapGetters, mapState } from 'vuex'

  export default {
    components: {
      VHeader
    },
    data () {
      return {
        dialogFlag: false,
        bindDialogFlag: false,
        // unBindDialogFlag: false,
        height: null,
        tableData: [],
        loading: true,
        dialogTitle: 'bind',
        title: '',
        // isPublish: false, // 是否发布的状态 发布状态按钮禁用
        dateValue: '',
        // currentTableData: {},
        saveCurrentGroup: '', // 保存单选选中的数据
        groupData: {
          // groupId: '',
          // groupName: '',
          // groupType: 'ws'
          groupId: '',
          workspaceId: ''
        },
        searchDataGroup: {
          startTime: '',
          endTime: '',
          deviceType: '',
          systemType: ''
        },
        workSpList: [],
        whiteList: [],
        workSelectValue: '',
        whiteSelectValue: '',
        bindGroupData: [],
        unBindGroupData: [],
        selectData: [],
        initData: [],
        userIdArr: [],
        filterArr: [],
        workSPAddRules: rules.workSPAddRules,
        currentPage: 1,
        pagesize: 10,
        totalCount: null,
        pickerOptions1: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          },
          shortcuts: [{
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }]
        }
        // selectCity: ''
      }
    },
    filters: {
      capitalize (val) {
        let date = new Date(val)
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
        let H = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
        let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
        let s = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds()
        return Y + M + D + H + m + s
      }
    },
    computed: {
      ...mapGetters([
        'workspaceId',
        'workspaceName'
      ]),
      ...mapState([
        'appId'
      ])
    },
    methods: {
      handlePublishClick (scope) {
        this.$confirm('是否确定发布', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // let params = {
          //   workspaceId: this.appId, // '20170906V1.0.0'
          //   groupId: scope.groupId
          // }
          let scopeId = []
          scopeId.push(scope.id)
          let params = {
            effected: !scope.effected,
            ids: scopeId
          }
          // this.handleInsertWork(params)
          this.handleRepeal(params)
        }).catch(() => {})
      },
      handleRepealClick (scope) {
        this.$confirm('是否置为失效', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let scopeId = []
          scopeId.push(scope.id)
          let params = {
            effected: !scope.effected,
            ids: scopeId
          }
          console.log(params)
          this.handleRepeal(params)
        }).catch(() => {})
      },
      handleRepeal (params) {
        // { "effected": true, "ids": ["1b8dfcde64b04832a0925e433a211dcc"] }
        ajax.post(api.UPDATE_WORKSPACE_GRAY_PUBLISH_STATE, params).then(res => {
          console.log(res)
          // if (res.data === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.queryGroupList()
          // }
        })
      },
      handleInsertWork (params) {
        ajax.post(api.INSERT_WORKSPACE_GROUP, params).then(res => {
          if (res.data === 1) {
            this.$message({
              type: 'success',
              message: '发布成功!'
            })
            this.queryGroupList()
          }
        })
      },
      queryGroupList (pageNo = 1, pageSize = 10) {
        ajax.post(api.LIST_WORKSPACE, {pageNo: pageNo, pageSize: pageSize}).then(res => {
          if (res.data.list.length >= 0) {
            this.tableData = res.data.list
            this.totalCount = res.data.total
            this.currentTableData = {...this.tableData}
          }
          this.loading = false
        })
      },
      // *****************************************************
      // 增加用户分组不全选手动选则一条或多条
      select (seletion) {
        this.selectData = seletion
      },
      // 增加用户分组全选
      selectAll (selection) {
        this.selectData = selection
      },
      // 增加用户分组
      addGruop () {
        // console.log(this.workspace_id)
        // console.log(this.workspaceName)
        this.dialogFlag = true
        // ajax.post(api.SEARCH_LIST_GROUP, {groupType: 'app', pageNo: 1, pageSize: 10000}).then(res => {
        //   arr = res.data.list.map(item => {
        //     return {'groupName': item.groupName, 'groupId': item.id}
        //   })
        //   this.whiteList = arr
        //   console.log(this.whiteList)
        // })
        ajax.post(api.GRAY_USER_GROUP_FILTER, {groupType: 'ws'}).then(res => {
          console.log(res)
          this.whiteList = res.data
          // arr = res.data.list.map(item => {
          //   return {'groupName': item.groupName, 'groupId': item.id}
          // })
          // this.whiteList = arr
          // console.log(this.whiteList)
        })
        ajax.get('/iap/workspaces?AppId=APP1').then(res => {
          this.workSpList = res.Workspaces
        })
      },
      // 单选
      handleCurrentChange (currentRow) {
        this.saveCurrentGroup = currentRow
      },
      // 编辑
      // modifyGruop () {
      //   this.title = 'MODIFY'
      //   if (this.saveCurrentGroup) {
      //     this.dialogFlag = true
      //     this.groupData = {...this.saveCurrentGroup}
      //   } else {
      //     this.$alert('请选择一个用户分群组', '温馨提示')
      //   }
      // },
      // 删除用户分组
      // deleteGruop () {
      //   if (this.saveCurrentGroup) {
      //     this.$confirm('确定要删除该项吗？', '提示', {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'warning'
      //     }).then(() => {
      //       let arr = []
      //       arr.push(this.saveCurrentGroup.groupId)
      //       ajax.post(api.DELETE_GROUP, { groupIds: arr, groupType: 'ws' }).then(res => {
      //         if (res.status === '000000') {
      //           this.$message({
      //             type: 'success',
      //             message: '删除成功'
      //           })
      //           this.queryGroupList()
      //         }
      //       })
      //     })
      //   } else {
      //     this.$alert('请选择一个用户分群组', '温馨提示')
      //   }
      // },
      // 分页
      currentChange (val) {
        this.currentPage = val
        this.queryGroupList(val)
      },
      // 查询当前组内的所有用户未绑定
      bindUser (para) {
        this.dialogTitle = 'bind'
        if (this.saveCurrentGroup) {
          this.selectData = []
          ajax.post(api.SEARCH_UNBIND_USER, para, true).then(res => {
            this.unBindGroupData = res.data
            this.bindDialogFlag = true
          }).catch(err => {
            this.$confirm({
              type: '提示',
              message: err.message
            })
          })
        } else {
          this.$alert('请选择一个用户分群组', '温馨提示')
        }
      },
      // 解除绑定
      unBind (para) {
        this.dialogTitle = 'unbind'
        if (this.saveCurrentGroup) {
          ajax.post(api.SEARCH_CURRENT_ALL_USER, {groupId: this.saveCurrentGroup.groupId}).then(res => {
            this.bindGroupData = res.data
            // this.unBindDialogFlag = true
            this.bindDialogFlag = true
            this.bindGroupData.forEach(item => {
              this.userIdArr.push(item.id)
            })
          })
        } else {
          this.$alert('请选择一个用户分群组', '温馨提示')
        }
      },
      // 重置
      rest () {
        if (this.title === 'ADD') {
          this.groupData = {}
          this.$refs.groupForm.clearValidate()
        } else {
          this.groupData = {...this.saveCurrentGroup}
          this.$refs.groupForm.clearValidate()
        }
      },
      // 关闭
      close () {
        this.dialogFlag = false
        this.groupData = {}
        this.$refs.groupForm.clearValidate()
      },
      bindClose () {
        this.selectData = []
        this.bindDialogFlag = false
      },
      // 确定
      submit () {
        this.$refs.groupForm.validate(valid => {
          if (valid) {
            // this.groupData['groupType'] = 'ws'
            // if (this.title === 'ADD') {
              // ajax.post(api.ADD_GROUP, this.groupData).then(res => {
              //   if (res.status === '000000') {
              //     this.$message({
              //       type: 'success',
              //       message: '增加成功'
              //     })
              //     this.queryGroupList(this.currentPage)
              //     this.dialogFlag = false
              //     this.groupData = {}
              //     this.$refs.groupForm.clearValidate()
              //   }
              // }).catch(err => {
              //   console.info(err)
              // })
            ajax.post(api.INSERT_WORKSPACE_GROUP, this.groupData).then(res => {
                this.$message({
                  type: 'success',
                  message: res.msg
                })
                this.queryGroupList()
                this.dialogFlag = false
            })
          }
        })
      },
      // 绑定用户的确定
      bindSubmit () {
        let postArr = []
        this.selectData.forEach(item => {
          let userId = item.id
          let groupId = this.saveCurrentGroup.groupId
          let groupName = this.saveCurrentGroup.groupName
          let postData = {
            user_id: userId,
            group_id: groupId,
            group_name: groupName
          }
          postArr.push(postData)
        })
        postArr['groupType'] = 'ws'
        if (this.selectData.length !== 0) {
          ajax.post(api.ADD_USER_USERGROUP, postArr).then(res => {
            if (res.status === '000000') {
              this.$message({
                type: 'success',
                message: '新增绑定成功'
              })
            }
          })
        } else {
          this.$message({
            type: 'warning',
            message: '未执行操作'
          })
        }
        this.bindDialogFlag = false
        this.selectData = []
      },
      // 解除绑定的确定
      unBindSubmit () {
        if (this.selectData.length !== 0) {
          ajax.post(api.DELETE_USER_USERGROUP, this.changeData(this.selectData)).then(res => {
            this.$message({
              type: 'success',
              message: '解绑成功'
            })
          })
        } else {
          this.$message({
            type: 'warning',
            message: '未执行操作'
          })
        }
        this.bindDialogFlag = false
        this.selectData = []
      },
      // 勾选
      changeData (selection) {
        this.filterArr = selection.map(item => {
          return item.id
        })
        return this.filterArr
      },
      searchUser () {
        this.bindUser(this.searchDataGroup)
      }
    },
    created () {
      this.queryGroupList()
    }
  }
</script>
<style lang="stylus" rel="stylesheet/stylus">
  #grayPublish
    height 100%
    overflow hidden
    .container-box
      height 100%
      overflow auto
    .toolbar
      height 58px
      background #ffffff
      line-height 58px
      padding 0 15px
      margin 10px 0 10px 10px
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
    .main-cont
      margin 10px 0 0 10px
      height 100%
    .el-dialog
      .el-dialog__body
        padding-bottom 50px !important
        .detailListStyle
          width 860px
          text-align center
          word-break break-all
    .f-rt
      margin-top 15px
      float right
    .el-button--text
      width 30px
    .el-row
      margin-bottom 20px
    .el-date-editor
      width auto !important
</style>
